package com.kis.controller;

import com.kis.dao.ServerDao;
import com.kis.pojo.ServerAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Created by wongloong on 16-5-24.
 */
@Controller
@RequestMapping("/server")
public class Index {
    @Autowired
    private ServerDao serverDao;

    @RequestMapping("/add")
    public void addServerAndRuntime(HttpServletRequest request, String mac) {
        ServerAddress serverAddress = new ServerAddress();
        serverAddress.setMac(mac);
        serverAddress.setIp(getIpAddr(request));
        serverAddress.setRuntime(new Date());
        serverDao.save(serverAddress);
    }

    /**
     * 获取访问者IP
     * <p>
     * 在一般情况下使用Request.getRemoteAddr()即可，但是经过nginx等反向代理软件后，这个方法会失效。
     * <p>
     * 本方法先从Header中获取X-Real-IP，如果不存在再从X-Forwarded-For获得第一个IP(用,分割)，
     * 如果还不存在则调用Request .getRemoteAddr()。
     *
     * @param request
     * @return
     */
    public  String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if (isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }

        if (isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        } else {
            /**
             *
             * 多次反向代理后会有多个IP值，第一个为真实IP。
             */
            int index = ip.indexOf(',');
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        return ip;
    }

    private boolean isBlank(String str) {
        if (null == str || str.length() == 0) {
            return true;
        }
        return false;
    }
}
